<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="resources/testharness-adapter.js"></script>
</head>
<body>
<script type="module">
import {GeolocationMock} from './resources/geolocation-mock.js';

description("Tests that watchPosition correctly reports position updates and errors from the Geolocation service.");

let mockLatitude = 51.478;
let mockLongitude = -0.166;
let mockAccuracy = 100.0;

const mockMessage = 'test';

let position;
let error;

function checkPosition(p) {
    position = p;
    assert_equals(position.coords.latitude, mockLatitude);
    assert_equals(position.coords.longitude, mockLongitude);
    assert_equals(position.coords.accuracy, mockAccuracy);
}

function checkError(e) {
    error = e;
    assert_equals(error.code, error.POSITION_UNAVAILABLE);
    assert_equals(error.message, mockMessage);
}

const mock = new GeolocationMock();
mock.setGeolocationPermission(true);
mock.setGeolocationPosition(mockLatitude, mockLongitude, mockAccuracy);

let state = 0;
navigator.geolocation.watchPosition(function(p) {
    switch (state++) {
        case 0:
            checkPosition(p);
            mock.setGeolocationPosition(++mockLatitude, ++mockLongitude, ++mockAccuracy);
            break;
        case 1:
            checkPosition(p);
            mock.setGeolocationPositionUnavailableError(mockMessage);
            break;
        case 3:
            checkPosition(p);
            finishJSTest();
            break;
        default:
            testFailed('Success callback invoked unexpectedly');
            finishJSTest();
    }
}, function(e) {
    switch (state++) {
        case 2:
            checkError(e);
            mock.setGeolocationPosition(++mockLatitude, ++mockLongitude, ++mockAccuracy);
            break;
        default:
            testFailed('Error callback invoked unexpectedly');
            finishJSTest();
    }
});
</script>
</body>
</html>
